from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
from model.fields.uBlobTaskField import BlobTaskField
from model.fields.uDeadLineTaskField import DeadLineTaskField
from model.fields.uTextTaskField import TextTaskField
from model.uTask import Task
from model.uUserAdapter import UserAdapter
from view.renderers.uMainPageRen import MainPageRen
from view.renderers.uNewCategoryRen import NewCategoryRen
from view.renderers.uNewTaskRen import NewTaskRen
import datetime
import os
import uConst


class MainPage(webapp.RequestHandler):
    
    def get(self):
        self.path = os.path.dirname(__file__)
        
        renderer = MainPageRen(self)
        renderer.render()
        

class NewCategory(webapp.RequestHandler):
    
    def post(self):
        user = UserAdapter(self)
        if user.isLogged():
            self.path=os.path.dirname(__file__)
            renderer = NewCategoryRen(self.request.get('category_name'),int(self.request.get('fields_quantity')),self)
            renderer.render()
        else:
            user.LogIn()
            

class SaveCategory(webapp.RequestHandler):
    
    def post(self):
        
        user = UserAdapter(self)
        
        if user.isLogged():
            
            aCategory = user.createCategory(self.request.get('category_name'))
            fieldQuantity = int(self.request.get('field_quantity'))
            for i in range(fieldQuantity):
                aName = self.request.get('field' + str(i))
                aType =int(self.request.get('type' + str(i)))
                
                if self.request.get('field' + str(i) + '_req'):
                    aReq = (self.request.get('field' + str(i) + '_req')  == 'on')
                else:
                    aReq = False
                
                aCategory.addField(aName, aType, aReq)
                
            self.redirect('/')
            
        else:
            user.LogIn()
            
class NewTask(webapp.RequestHandler):
    
    def post(self):
        user = UserAdapter(self)
        if user.isLogged():
            self.path=os.path.dirname(__file__)
            catKey = self.request.get('task_category')
            aTask=user.createTask(self.request.get('task_name'),user.getCategoryByKey(catKey))
            aTask.setCreationDate(datetime.datetime.now())
            renderer = NewTaskRen(self,aTask)
            renderer.render()
        else:
            user.LogIn()
            
class SaveTask(webapp.RequestHandler):
    
    def post(self):
        user = UserAdapter(self)
        if user.isLogged():
            
            aTask = user.getTaskByKey(self.request.get('task_key'))
            aTask.setUpdateDate(datetime.datetime.today(),user.getAdaptedUser())
            
            for aField in aTask.getFields():
                key = str(aField.key())
                if not isinstance(aField, BlobTaskField):
                    if self.request.get(key)!='':
                        aField.setValue(self.request.get(key))
                        if isinstance(aField, DeadLineTaskField):
                            aField.setMessage(self.request.get(key + '_m'))
                    
            self.redirect('/')
            
        else:
            user.LogIn()
            
class DeleteTask(webapp.RequestHandler):
    
    def get(self):
        user = UserAdapter(self)
        if user.isLogged():
            user.deleteTask(user.getTaskByKey(self.request.get('task_key')))
            self.redirect('/')
        else:
            user.logIn()
            
class UpdateTask(webapp.RequestHandler):
    
    def get(self):
        user = UserAdapter(self)
        if user.isLogged():
            self.path=os.path.dirname(__file__)
            renderer = NewTaskRen(self, user.getTaskByKey(self.request.get('task_key')))
            renderer.render()
        else:
            user.LogIn()
            
class ChangeCompletedState(webapp.RequestHandler):
    
    def get(self):
        user = UserAdapter(self)
        if user.isLogged():
            user.getTaskByKey(self.request.get('task_key')).changeCompletedState()
            self.redirect('/')
        else:
            user.LogIn()
            
class UserLogOut(webapp.RequestHandler):
    
    def get(self):
        user = UserAdapter(self)
        if user.isLogged():
            user.LogOut()
        else:
            user.LogIn()
            
class ShareTask(webapp.RequestHandler):
    
    def post(self):
        user = UserAdapter(self)
        if user.isLogged():
            aTask = user.getTaskByKey(self.request.get('task_key'))
            if aTask.getParent()==None:
                if aTask.getSubTasks():
                    for itTask in aTask.getSubTasks():
                        itTask.addSharedUser(self.request.get('user_email'))
                aTask.addSharedUser(self.request.get('user_email'))
                self.redirect('/')
            else:
                print 'No es posible compartir una tarea que no se encuentra en la Raiz'
        else:
            user.LogIn()
            
class ChangeTaskParent(webapp.RequestHandler):
    
    def get(self):
        user = UserAdapter(self)
        if user.isLogged():
            aChild = user.getTaskByKey(self.request.get('task_child_key'))
            aParent = user.getTaskByKey(self.request.get('task_parent_key'))
            aChild.setParent(aParent)
            self.redirect('/?position='+str(aParent.key()))
        else:
            user.LogIn()
            
class UpTaskPosition(webapp.RequestHandler):
    
    def get(self):
        user = UserAdapter(self)
        if user.isLogged():
            aChild = user.getTaskByKey(self.request.get('task_child_key'))
            if aChild.getParent():
                newParent = aChild.getParent().getParent()
                aChild.setParent(newParent)
            else:
                newParent = None
            if newParent:
                self.redirect('/?position='+str(newParent.key()))
            else:
                self.redirect('/')
            
        else:
            user.LogIn()

class DeleteCategory(webapp.RequestHandler):
    
    def get(self):
        user = UserAdapter(self)
        if user.isLogged():
            user.deleteCategory(user.getCategoryByKey(self.request.get('category_key')))
            self.redirect('/')
        else:
            user.LogIn()
    
        
class Welcome(webapp.RequestHandler):
    def get(self):
        path = os.path.join(os.path.dirname(__file__), 'view/login.html')
        self.response.out.write(template.render(path,[]))
        
class Login(webapp.RequestHandler):
    def get(self):
        self.redirect(users.create_login_url('/'))
        
class PrintTask(webapp.RequestHandler):
    def get(self):
        user=UserAdapter(self)
        if user.isLogged():
            if self.request.get('task_key'):
                list = user.getTaskByKey(self.request.get('task_key')).toRenderable()
            else:
                list = []
                for aTask in user.getTaskList():
                    list = list + aTask.toRenderable()
            values = { 'task_list':list, }    
            path = os.path.join(os.path.dirname(__file__), 'view/print.html')
            self.response.out.write(template.render(path,values))
        else:
            user.LogIn()
            
class ChangeConf(webapp.RequestHandler):
    def get(self):
        user=UserAdapter(self)
        if user.isLogged():
            user.getConf().setTheme(self.request.get('theme'))
            self.redirect('/')
        else:
            user.LogIn()
      
        
        


application = webapp.WSGIApplication([
                                    
                                      ('/', MainPage), 
                                      ('/new_category', NewCategory), 
                                      ('/save_category',SaveCategory),
                                      ('/save_task',SaveTask),
                                      ('/new_task', NewTask),
                                      ('/delete_task',DeleteTask),
                                      ('/update_task',UpdateTask),
                                      ('/change_completed_state',ChangeCompletedState),
                                      ('/user_logout',UserLogOut),
                                      ('/share_task',ShareTask),
                                      ('/change_task_parent',ChangeTaskParent),
                                      ('/up_task_position',UpTaskPosition),
                                      ('/delete_category',DeleteCategory),
                                      ('/welcome',Welcome),
                                      ('/login',Login),
                                      ('/print_task',PrintTask),
                                      ('/change_conf',ChangeConf)

                                     ], debug=True)


def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
